package com.taotao.search.service.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.taotao.pojo.TaotaoResult;
import com.taotao.search.dao.SearchDao;
import com.taotao.search.mapper.ItemMapper;
import com.taotao.search.pojo.SearchItem;
import com.taotao.search.pojo.SearchResult;
import com.taotao.search.service.ItemService;

@Service
public class ItemServiceImpl implements ItemService {

	@Autowired
	private ItemMapper itemMapper;
	
	@Autowired
	private SearchDao searchDao;
	
	@Autowired
	private HttpSolrServer httpSolrServer;
	
	@Override
	public TaotaoResult importItem() throws Exception{
		
		// 查询数据
		List<SearchItem> itemList = itemMapper.getItemList();
		if (itemList==null) {
			return TaotaoResult.build(500, "查出来的商品为空");
		}		
		for (SearchItem item : itemList) {
			// 创建文档对象
			SolrInputDocument doc= new SolrInputDocument();
			//添加域
			doc.addField("id", item.getId());
			doc.addField("item_title", item.getTitle());
			doc.addField("item_sell_point", item.getSell_point());
			doc.addField("item_price", item.getPrice());
			doc.addField("item_image", item.getImage());
			doc.addField("item_category_name", item.getCategory_name());
			doc.addField("item_desc", item.getDesc());
			httpSolrServer.add(doc);
		}
		// 一定要提交
		httpSolrServer.commit();
		return TaotaoResult.ok();
	}

	/**
	 * 根据查询条件返回查询结果
	 */
	@Override
	public SearchResult queryItem(String queryString, Integer currentPage,
			Integer rows) throws Exception {
		
		// 如果查询条件等于空 就默认查询所以的商品信息
		if (StringUtils.isBlank(queryString)) {
			queryString="*:*";
		}
		
		// 组拼查询条件
		SolrQuery query = new SolrQuery();
		// 设置查询条件
		query.setQuery(queryString);
		
		// 设置分页查询的开始索引
		query.setStart((currentPage-1)*rows);
		query.setRows(rows);
		
		// 设置默认搜索域
		query.set("df", "item_keywords");
		
		// 设置高亮信息
		query.setHighlight(true);
		query.addHighlightField("item_title");
		query.setHighlightSimplePre("<font class=\"skcolor_ljg\">");
		query.setHighlightSimplePost("</font>");
		
		// 执行查询
		SearchResult result = searchDao.search(query);
		
		// 设置总页数
		Long total = result.getTotal();
		
		// 总记录数加上行数减一1 去整
		result.setPageCount((int) (total+(rows-1))/rows);	
		return result;
	}

}
